package netWork;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * Created with IntelliJ IDEA.
 * Description: 回显服务器的服务端
 * User: 王圆豪
 * Date: 2025-05-14
 * Time: 17:22
 */
public class UdpEchoServer {
    private DatagramSocket socket = null;

    public UdpEchoServer(int port) throws SocketException {
        socket = new DatagramSocket(port);
    }
    public void start() throws IOException {
        //启动服务器
        System.out.println("服务器已启动！");

        while (true) {
            //1.获取请求并解析
            DatagramPacket requestPacket = new DatagramPacket(new byte[4029], 4029);
            socket.receive(requestPacket);
            String request = new String(requestPacket.getData(), 0, requestPacket.getLength());

            //根据请求计算响应
            String response = process(request);

            //把响应结果返回给客户端
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes()
                    , response.getBytes().length, requestPacket.getSocketAddress());

            socket.send(responsePacket);

            //打印日志
            System.out.printf("[%s:%d] req: %s, resp: %s\n", requestPacket.getAddress(),
                    requestPacket.getPort(),request, response);
        }
    }

    public String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServer server = new UdpEchoServer(9090);
        server.start();
    }
}
